//
//  PopoverAnimator.swift
//  iOS07-Weibo-LPK
//
//  Created by 罗培克 on 6/27/15.
//  Copyright © 2015 lpk. All rights reserved.
//

import UIKit

class PopoverAnimator: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    /// 展现视图的大小
    var presentFrame = CGRectZero
    /// 是否展现
    var isPresented = false
    
    /// 返回负责转场的控制器
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        let pc = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
        pc.presentFrame = presentFrame
        
        return pc
    }
    
    /// 返回提供 modal 的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        
        return self
    }
     /// 返回提供 dismissed 动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        
        return self
    }
    
    /// 返回动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 1.2
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 判断是 modal 还是 dismissed
        if isPresented {
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            // 1. 将 toView 添加到容器视图
            transitionContext.containerView().addSubview(toView)
            
            // 2. 动画实现
            toView.transform = CGAffineTransformMakeScale(1.0, 0)
            toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
                toView.transform = CGAffineTransformIdentity
                }, completion: { (_) -> Void in
                    // 3. ----结束动画-----
                    transitionContext.completeTransition(true)
            })
        } else {
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            fromView.removeFromSuperview()
            
            transitionContext.completeTransition(true)
        }
    }
}
